package net.didactylos.helpline.action;

import org.hibernate.*;

import net.didactylos.helpline.data.*;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.didactylos.helpline.stripes.security.Capabilities;
import net.didactylos.helpline.stripes.security.Secured;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.*;

public class EditContactAction extends HelplineActionBean
{
    @ValidateNestedProperties({
        @Validate(field="firstNames", maxlength=50),
        @Validate(field="lastName", maxlength=50),
        @Validate(field="emailAddress", maxlength=50, converter=EmailTypeConverter.class)
    })
	private Contact newUser;
    
	public Contact getNewUser()
	{
		return newUser;
	}

	public void setNewUser(Contact newUser)
	{
		this.newUser = newUser;
	}
	
	@After(stages=LifecycleStage.BindingAndValidation)
	public void preLoad()
	{
//		if (newUser == null)
//		{
//			Session session = getContext().getSession();
//			newUser = (User) session.get(User.class, userId);
//			roleId = newUser.getRole().getId();
//		}
	}

	@Secured(Capabilities.SIGN_IN)
	public Resolution editContact()
	{
		net.didactylos.helpline.data.Message message = getContext().getMessage();
		
		Session session = getContext().getSession();
		
		EmailContact original = message.getAuthor();
		
		if ((newUser.getEmailAddress() == null) || original.getEmailAddress().equals(newUser.getEmailAddress()))
		{
			original.setFirstNames(newUser.getFirstNames());
			original.setLastName(newUser.getLastName());
			session.update(original);
		}
		else
		{
			message.setAuthor(newUser);
			session.save(newUser);
			session.update(message);
		}
        
		return new RedirectResolution("/Reply.action");
	}

}
